// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers.  See the top-level LICENSE file for dates and other
// details.  No copyright assignment is required to contribute to VisIt.

#include <PySelectionList.h>
#include <ObserverToCallback.h>
#include <stdio.h>
#include <Py2and3Support.h>
#include <PySelectionProperties.h>
#include <PySelectionSummary.h>

// ****************************************************************************
// Module: PySelectionList
//
// Purpose:
//   Contains a list of SelectionProperties objects.
//
// Note:       Autogenerated by xml2python. Do not modify by hand!
//
// Programmer: xml2python
// Creation:   omitted
//
// ****************************************************************************

//
// This struct contains the Python type information and a SelectionList.
//
struct SelectionListObject
{
    PyObject_HEAD
    SelectionList *data;
    bool        owns;
    PyObject   *parent;
};

//
// Internal prototypes
//
static PyObject *NewSelectionList(int);
std::string
PySelectionList_ToString(const SelectionList *atts, const char *prefix, const bool forLogging)
{
    std::string str;
    char tmpStr[1000];

    if(atts->GetAutoApplyUpdates())
        snprintf(tmpStr, 1000, "%sautoApplyUpdates = 1\n", prefix);
    else
        snprintf(tmpStr, 1000, "%sautoApplyUpdates = 0\n", prefix);
    str += tmpStr;
    { // new scope
        int index = 0;
        // Create string representation of selections from atts.
        for(AttributeGroupVector::const_iterator pos = atts->GetSelections().begin(); pos != atts->GetSelections().end(); ++pos, ++index)
        {
            const SelectionProperties *current = (const SelectionProperties *)(*pos);
            snprintf(tmpStr, 1000, "GetSelections(%d).", index);
            std::string objPrefix(prefix + std::string(tmpStr));
            str += PySelectionProperties_ToString(current, objPrefix.c_str(), forLogging);
        }
        if(index == 0)
            str += "#selections does not contain any SelectionProperties objects.\n";
    }
    { // new scope
        int index = 0;
        // Create string representation of selectionSummary from atts.
        for(AttributeGroupVector::const_iterator pos = atts->GetSelectionSummary().begin(); pos != atts->GetSelectionSummary().end(); ++pos, ++index)
        {
            const SelectionSummary *current = (const SelectionSummary *)(*pos);
            snprintf(tmpStr, 1000, "GetSelectionSummary(%d).", index);
            std::string objPrefix(prefix + std::string(tmpStr));
            str += PySelectionSummary_ToString(current, objPrefix.c_str(), forLogging);
        }
        if(index == 0)
            str += "#selectionSummary does not contain any SelectionSummary objects.\n";
    }
    return str;
}

static PyObject *
SelectionList_Notify(PyObject *self, PyObject *args)
{
    SelectionListObject *obj = (SelectionListObject *)self;
    obj->data->Notify();
    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
SelectionList_SetAutoApplyUpdates(PyObject *self, PyObject *args)
{
    SelectionListObject *obj = (SelectionListObject *)self;

    PyObject *packaged_args = 0;

    // Handle args packaged into a tuple of size one
    // if we think the unpackaged args matches our needs
    if (PySequence_Check(args) && PySequence_Size(args) == 1)
    {
        packaged_args = PySequence_GetItem(args, 0);
        if (PyNumber_Check(packaged_args))
            args = packaged_args;
    }

    if (PySequence_Check(args))
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_TypeError, "expecting a single number arg");
    }

    if (!PyNumber_Check(args))
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_TypeError, "arg is not a number type");
    }

    long val = PyLong_AsLong(args);
    bool cval = bool(val);

    if (val == -1 && PyErr_Occurred())
    {
        Py_XDECREF(packaged_args);
        PyErr_Clear();
        return PyErr_Format(PyExc_TypeError, "arg not interpretable as C++ bool");
    }
    if (fabs(double(val))>1.5E-7 && fabs((double(long(cval))-double(val))/double(val))>1.5E-7)
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_ValueError, "arg not interpretable as C++ bool");
    }

    Py_XDECREF(packaged_args);

    // Set the autoApplyUpdates in the object.
    obj->data->SetAutoApplyUpdates(cval);

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
SelectionList_GetAutoApplyUpdates(PyObject *self, PyObject *args)
{
    SelectionListObject *obj = (SelectionListObject *)self;
    PyObject *retval = PyInt_FromLong(obj->data->GetAutoApplyUpdates()?1L:0L);
    return retval;
}

/*static*/ PyObject *
SelectionList_GetSelections(PyObject *self, PyObject *args)
{
    SelectionListObject *obj = (SelectionListObject *)self;
    int index = -1;
    if (args == NULL)
        return PyErr_Format(PyExc_NameError, "Use .GetSelections(int index) to get a single entry");
    if (!PyArg_ParseTuple(args, "i", &index))
        return PyErr_Format(PyExc_TypeError, "arg must be a single integer index");
    if (index < 0 || (size_t)index >= obj->data->GetSelections().size())
        return PyErr_Format(PyExc_ValueError, "index out of range");

    // Since the new object will point to data owned by the this object,
    // we need to increment the reference count.
    Py_INCREF(self);

    PyObject *retval = PySelectionProperties_Wrap(&obj->data->GetSelections(index));
    // Set the object's parent so the reference to the parent can be decref'd
    // when the child goes out of scope.
    PySelectionProperties_SetParent(retval, self);

    return retval;
}

PyObject *
SelectionList_GetNumSelections(PyObject *self, PyObject *args)
{
    SelectionListObject *obj = (SelectionListObject *)self;
    return PyInt_FromLong((long)obj->data->GetSelections().size());
}

PyObject *
SelectionList_AddSelections(PyObject *self, PyObject *args)
{
    SelectionListObject *obj = (SelectionListObject *)self;
    PyObject *element = NULL;
    if(!PyArg_ParseTuple(args, "O", &element))
        return NULL;
    if(!PySelectionProperties_Check(element))
        return PyErr_Format(PyExc_TypeError, "expected attr object of type SelectionProperties");
    SelectionProperties *newData = PySelectionProperties_FromPyObject(element);
    obj->data->AddSelections(*newData);
    obj->data->SelectSelections();
    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
SelectionList_Remove_One_Selections(PyObject *self, int index)
{
    SelectionListObject *obj = (SelectionListObject *)self;
    // Remove in the AttributeGroupVector instead of calling RemoveSelections() because we don't want to delete the object; just remove it.
    AttributeGroupVector &atts = obj->data->GetSelections();
    AttributeGroupVector::iterator pos = atts.begin();
    // Iterate through the vector "index" times.
    for(int i = 0; i < index; ++i)
        ++pos;

    // If pos is still a valid iterator, remove that element.
    if(pos != atts.end())
    {
        // NOTE: Leak the object since other Python objects may reference it. Ideally,
        // we would put the object into some type of pool to be cleaned up later but
        // this will do for now.
        //
        // delete *pos;
        atts.erase(pos);
    }

    obj->data->SelectSelections();
    Py_INCREF(Py_None);
    return Py_None;
}

PyObject *
SelectionList_RemoveSelections(PyObject *self, PyObject *args)
{
    int index = -1;
    if(!PyArg_ParseTuple(args, "i", &index))
        return PyErr_Format(PyExc_TypeError, "Expecting integer index");
    SelectionListObject *obj = (SelectionListObject *)self;
    if(index < 0 || index >= obj->data->GetNumSelections())
        return PyErr_Format(PyExc_IndexError, "Index out of range");

    return SelectionList_Remove_One_Selections(self, index);
}

PyObject *
SelectionList_ClearSelections(PyObject *self, PyObject *args)
{
    SelectionListObject *obj = (SelectionListObject *)self;
    int n = obj->data->GetNumSelections();
    for(int i = 0; i < n; ++i)
    {
        SelectionList_Remove_One_Selections(self, 0);
        Py_DECREF(Py_None);
    }
    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
SelectionList_GetSelectionSummary(PyObject *self, PyObject *args)
{
    SelectionListObject *obj = (SelectionListObject *)self;
    int index = -1;
    if (args == NULL)
        return PyErr_Format(PyExc_NameError, "Use .GetSelectionSummary(int index) to get a single entry");
    if (!PyArg_ParseTuple(args, "i", &index))
        return PyErr_Format(PyExc_TypeError, "arg must be a single integer index");
    if (index < 0 || (size_t)index >= obj->data->GetSelectionSummary().size())
        return PyErr_Format(PyExc_ValueError, "index out of range");

    // Since the new object will point to data owned by the this object,
    // we need to increment the reference count.
    Py_INCREF(self);

    PyObject *retval = PySelectionSummary_Wrap(&obj->data->GetSelectionSummary(index));
    // Set the object's parent so the reference to the parent can be decref'd
    // when the child goes out of scope.
    PySelectionSummary_SetParent(retval, self);

    return retval;
}

PyObject *
SelectionList_GetNumSelectionSummary(PyObject *self, PyObject *args)
{
    SelectionListObject *obj = (SelectionListObject *)self;
    return PyInt_FromLong((long)obj->data->GetSelectionSummary().size());
}

PyObject *
SelectionList_AddSelectionSummary(PyObject *self, PyObject *args)
{
    SelectionListObject *obj = (SelectionListObject *)self;
    PyObject *element = NULL;
    if(!PyArg_ParseTuple(args, "O", &element))
        return NULL;
    if(!PySelectionSummary_Check(element))
        return PyErr_Format(PyExc_TypeError, "expected attr object of type SelectionSummary");
    SelectionSummary *newData = PySelectionSummary_FromPyObject(element);
    obj->data->AddSelectionSummary(*newData);
    obj->data->SelectSelectionSummary();
    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
SelectionList_Remove_One_SelectionSummary(PyObject *self, int index)
{
    SelectionListObject *obj = (SelectionListObject *)self;
    // Remove in the AttributeGroupVector instead of calling RemoveSelectionSummary() because we don't want to delete the object; just remove it.
    AttributeGroupVector &atts = obj->data->GetSelectionSummary();
    AttributeGroupVector::iterator pos = atts.begin();
    // Iterate through the vector "index" times.
    for(int i = 0; i < index; ++i)
        ++pos;

    // If pos is still a valid iterator, remove that element.
    if(pos != atts.end())
    {
        // NOTE: Leak the object since other Python objects may reference it. Ideally,
        // we would put the object into some type of pool to be cleaned up later but
        // this will do for now.
        //
        // delete *pos;
        atts.erase(pos);
    }

    obj->data->SelectSelectionSummary();
    Py_INCREF(Py_None);
    return Py_None;
}

PyObject *
SelectionList_RemoveSelectionSummary(PyObject *self, PyObject *args)
{
    int index = -1;
    if(!PyArg_ParseTuple(args, "i", &index))
        return PyErr_Format(PyExc_TypeError, "Expecting integer index");
    SelectionListObject *obj = (SelectionListObject *)self;
    if(index < 0 || index >= obj->data->GetNumSelectionSummarys())
        return PyErr_Format(PyExc_IndexError, "Index out of range");

    return SelectionList_Remove_One_SelectionSummary(self, index);
}

PyObject *
SelectionList_ClearSelectionSummary(PyObject *self, PyObject *args)
{
    SelectionListObject *obj = (SelectionListObject *)self;
    int n = obj->data->GetNumSelectionSummarys();
    for(int i = 0; i < n; ++i)
    {
        SelectionList_Remove_One_SelectionSummary(self, 0);
        Py_DECREF(Py_None);
    }
    Py_INCREF(Py_None);
    return Py_None;
}



PyMethodDef PySelectionList_methods[SELECTIONLIST_NMETH] = {
    {"Notify", SelectionList_Notify, METH_VARARGS},
    {"SetAutoApplyUpdates", SelectionList_SetAutoApplyUpdates, METH_VARARGS},
    {"GetAutoApplyUpdates", SelectionList_GetAutoApplyUpdates, METH_VARARGS},
    {"GetSelections", SelectionList_GetSelections, METH_VARARGS},
    {"GetNumSelections", SelectionList_GetNumSelections, METH_VARARGS},
    {"AddSelections", SelectionList_AddSelections, METH_VARARGS},
    {"RemoveSelections", SelectionList_RemoveSelections, METH_VARARGS},
    {"ClearSelections", SelectionList_ClearSelections, METH_VARARGS},
    {"GetSelectionSummary", SelectionList_GetSelectionSummary, METH_VARARGS},
    {"GetNumSelectionSummary", SelectionList_GetNumSelectionSummary, METH_VARARGS},
    {"AddSelectionSummary", SelectionList_AddSelectionSummary, METH_VARARGS},
    {"RemoveSelectionSummary", SelectionList_RemoveSelectionSummary, METH_VARARGS},
    {"ClearSelectionSummary", SelectionList_ClearSelectionSummary, METH_VARARGS},
    {NULL, NULL}
};

//
// Type functions
//

static void
SelectionList_dealloc(PyObject *v)
{
   SelectionListObject *obj = (SelectionListObject *)v;
   if(obj->parent != 0)
       Py_DECREF(obj->parent);
   if(obj->owns)
       delete obj->data;
}

static PyObject *SelectionList_richcompare(PyObject *self, PyObject *other, int op);
PyObject *
PySelectionList_getattr(PyObject *self, char *name)
{
    if(strcmp(name, "autoApplyUpdates") == 0)
        return SelectionList_GetAutoApplyUpdates(self, NULL);
    if(strcmp(name, "selections") == 0)
        return SelectionList_GetSelections(self, NULL);
    if(strcmp(name, "selectionSummary") == 0)
        return SelectionList_GetSelectionSummary(self, NULL);


    // Add a __dict__ answer so that dir() works
    if (!strcmp(name, "__dict__"))
    {
        PyObject *result = PyDict_New();
        for (int i = 0; PySelectionList_methods[i].ml_meth; i++)
            PyDict_SetItem(result,
                PyString_FromString(PySelectionList_methods[i].ml_name),
                PyString_FromString(PySelectionList_methods[i].ml_name));
        return result;
    }

    return Py_FindMethod(PySelectionList_methods, self, name);
}

int
PySelectionList_setattr(PyObject *self, char *name, PyObject *args)
{
    PyObject NULL_PY_OBJ;
    PyObject *obj = &NULL_PY_OBJ;

    if(strcmp(name, "autoApplyUpdates") == 0)
        obj = SelectionList_SetAutoApplyUpdates(self, args);

    if (obj != NULL && obj != &NULL_PY_OBJ)
        Py_DECREF(obj);

    if (obj == &NULL_PY_OBJ)
    {
        obj = NULL;
        PyErr_Format(PyExc_NameError, "name '%s' is not defined", name);
    }
    else if (obj == NULL && !PyErr_Occurred())
        PyErr_Format(PyExc_RuntimeError, "unknown problem with '%s'", name);

    return (obj != NULL) ? 0 : -1;
}

static int
SelectionList_print(PyObject *v, FILE *fp, int flags)
{
    SelectionListObject *obj = (SelectionListObject *)v;
    fprintf(fp, "%s", PySelectionList_ToString(obj->data, "",false).c_str());
    return 0;
}

PyObject *
SelectionList_str(PyObject *v)
{
    SelectionListObject *obj = (SelectionListObject *)v;
    return PyString_FromString(PySelectionList_ToString(obj->data,"", false).c_str());
}

//
// The doc string for the class.
//
#if PY_MAJOR_VERSION > 2 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 5)
static const char *SelectionList_Purpose = "Contains a list of SelectionProperties objects.";
#else
static char *SelectionList_Purpose = "Contains a list of SelectionProperties objects.";
#endif

//
// Python Type Struct Def Macro from Py2and3Support.h
//
//         VISIT_PY_TYPE_OBJ( VPY_TYPE,
//                            VPY_NAME,
//                            VPY_OBJECT,
//                            VPY_DEALLOC,
//                            VPY_PRINT,
//                            VPY_GETATTR,
//                            VPY_SETATTR,
//                            VPY_STR,
//                            VPY_PURPOSE,
//                            VPY_RICHCOMP,
//                            VPY_AS_NUMBER)

//
// The type description structure
//

VISIT_PY_TYPE_OBJ(SelectionListType,         \
                  "SelectionList",           \
                  SelectionListObject,       \
                  SelectionList_dealloc,     \
                  SelectionList_print,       \
                  PySelectionList_getattr,   \
                  PySelectionList_setattr,   \
                  SelectionList_str,         \
                  SelectionList_Purpose,     \
                  SelectionList_richcompare, \
                  0); /* as_number*/

//
// Helper function for comparing.
//
static PyObject *
SelectionList_richcompare(PyObject *self, PyObject *other, int op)
{
    // only compare against the same type 
    if ( Py_TYPE(self) != &SelectionListType
         || Py_TYPE(other) != &SelectionListType)
    {
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }

    PyObject *res = NULL;
    SelectionList *a = ((SelectionListObject *)self)->data;
    SelectionList *b = ((SelectionListObject *)other)->data;

    switch (op)
    {
       case Py_EQ:
           res = (*a == *b) ? Py_True : Py_False;
           break;
       case Py_NE:
           res = (*a != *b) ? Py_True : Py_False;
           break;
       default:
           res = Py_NotImplemented;
           break;
    }

    Py_INCREF(res);
    return res;
}

//
// Helper functions for object allocation.
//

static SelectionList *defaultAtts = 0;
static SelectionList *currentAtts = 0;

static PyObject *
NewSelectionList(int useCurrent)
{
    SelectionListObject *newObject;
    newObject = PyObject_NEW(SelectionListObject, &SelectionListType);
    if(newObject == NULL)
        return NULL;
    if(useCurrent && currentAtts != 0)
        newObject->data = new SelectionList(*currentAtts);
    else if(defaultAtts != 0)
        newObject->data = new SelectionList(*defaultAtts);
    else
        newObject->data = new SelectionList;
    newObject->owns = true;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

static PyObject *
WrapSelectionList(const SelectionList *attr)
{
    SelectionListObject *newObject;
    newObject = PyObject_NEW(SelectionListObject, &SelectionListType);
    if(newObject == NULL)
        return NULL;
    newObject->data = (SelectionList *)attr;
    newObject->owns = false;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

///////////////////////////////////////////////////////////////////////////////
//
// Interface that is exposed to the VisIt module.
//
///////////////////////////////////////////////////////////////////////////////

PyObject *
SelectionList_new(PyObject *self, PyObject *args)
{
    int useCurrent = 0;
    if (!PyArg_ParseTuple(args, "i", &useCurrent))
    {
        if (!PyArg_ParseTuple(args, ""))
            return NULL;
        else
            PyErr_Clear();
    }

    return (PyObject *)NewSelectionList(useCurrent);
}

//
// Plugin method table. These methods are added to the visitmodule's methods.
//
static PyMethodDef SelectionListMethods[] = {
    {"SelectionList", SelectionList_new, METH_VARARGS},
    {NULL,      NULL}        /* Sentinel */
};

static Observer *SelectionListObserver = 0;

std::string
PySelectionList_GetLogString()
{
    std::string s("SelectionList = SelectionList()\n");
    if(currentAtts != 0)
        s += PySelectionList_ToString(currentAtts, "SelectionList.", true);
    return s;
}

static void
PySelectionList_CallLogRoutine(Subject *subj, void *data)
{
    typedef void (*logCallback)(const std::string &);
    logCallback cb = (logCallback)data;

    if(cb != 0)
    {
        std::string s("SelectionList = SelectionList()\n");
        s += PySelectionList_ToString(currentAtts, "SelectionList.", true);
        cb(s);
    }
}

void
PySelectionList_StartUp(SelectionList *subj, void *data)
{
    if(subj == 0)
        return;

    currentAtts = subj;
    PySelectionList_SetDefaults(subj);

    //
    // Create the observer that will be notified when the attributes change.
    //
    if(SelectionListObserver == 0)
    {
        SelectionListObserver = new ObserverToCallback(subj,
            PySelectionList_CallLogRoutine, (void *)data);
    }

}

void
PySelectionList_CloseDown()
{
    delete defaultAtts;
    defaultAtts = 0;
    delete SelectionListObserver;
    SelectionListObserver = 0;
}

PyMethodDef *
PySelectionList_GetMethodTable(int *nMethods)
{
    *nMethods = 1;
    return SelectionListMethods;
}

bool
PySelectionList_Check(PyObject *obj)
{
    return (obj->ob_type == &SelectionListType);
}

SelectionList *
PySelectionList_FromPyObject(PyObject *obj)
{
    SelectionListObject *obj2 = (SelectionListObject *)obj;
    return obj2->data;
}

PyObject *
PySelectionList_New()
{
    return NewSelectionList(0);
}

PyObject *
PySelectionList_Wrap(const SelectionList *attr)
{
    return WrapSelectionList(attr);
}

void
PySelectionList_SetParent(PyObject *obj, PyObject *parent)
{
    SelectionListObject *obj2 = (SelectionListObject *)obj;
    obj2->parent = parent;
}

void
PySelectionList_SetDefaults(const SelectionList *atts)
{
    if(defaultAtts)
        delete defaultAtts;

    defaultAtts = new SelectionList(*atts);
}

